/* eslint-disable no-nested-ternary */
/* eslint-disable react/no-unused-state */
/* eslint-disable no-param-reassign */
/* eslint-disable no-prototype-builtins */
/* eslint-disable default-case */
import React, { Fragment } from 'react';
import {
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Col,
  Row,
  Button,
  Input,
  Select,
  Tabs,
  Modal,
  DatePicker,
  Divider,
  Menu,
  Dropdown,
} from 'antd';
import { connect } from 'dva';
import queryString from 'query-string';
import moment from 'moment';
import Link from 'umi/link';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import DictCode from '../../components/DictCode';
import styles from '../../../utils/utils.less';

const { Option } = Select;
const FormItem = Form.Item;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

@connect(({ material, loading }) => ({
  material,
  loading: loading.models.material,
}))
@Form.create()
class entrymaterial extends React.Component {
  state = {
    areaList: [],
    selectedRowKeys: [],
    selectedRows: [],
    formValues: {},
  };

  tableSearchLayout = {
    labelCol: {
      md: {
        span: 7,
      },
      lg: {
        span: 7,
      },
      xl: {
        span: 6,
      },
      xxl: {
        span: 4,
      },
    },
    wrapperCol: {
      md: {
        span: 17,
      },
      xxl: {
        span: 17,
      },
    },
  };

  componentDidMount = () => {
    const {
      location,
      material: {
        data: { pagination },
        activeKey = '1',
      },
      dispatch,
    } = this.props;
    const { isMenuLink } = location.query;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    dispatch({
      type: 'material/updateModelData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(tempActiveKey, pagination.current, pagination.pageSize);
    }
    this.changeArea();
  };

  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'material/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.setFieldsValue({
      dateArr: null,
    });
  };

  // 地区
  changeArea = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'material/fetchAreaList',
      payload: {},
    });
  };

  getList = (activeKey = '1', currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;
    form.validateFieldsAndScroll((err, fieldsValue) => {
      if (!err) {
        dispatch({
          type: 'material/updateModelData',
          payload: { formFieldsValue: fieldsValue, activeKey },
        });
        const formFieldsValue = {};
        Object.keys(fieldsValue).forEach(key => {
          if (fieldsValue.hasOwnProperty(key) && fieldsValue[key] === undefined) {
            formFieldsValue[key] = null;
          } else if (key === 'dateArr') {
            formFieldsValue.startTime = fieldsValue.dateArr
              ? fieldsValue.dateArr[0].valueOf()
              : null;
            formFieldsValue.endTime = fieldsValue.dateArr ? fieldsValue.dateArr[1].valueOf() : null;
            delete formFieldsValue[key];
          }
          if (key === 'areaId') {
            formFieldsValue.areaId = fieldsValue[key];
          }

          if (key === 'creName') {
            formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key].trim();
          } else {
            formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
          }
        });
        const pagerArg = { currentPage, pageSize };
        const filds = activeKey === '3' ? 'mat' : activeKey === '2' ? 'entryInformVo' : null;
        const values = filds
          ? {
              [filds]: formFieldsValue,
              pagerArg,
            }
          : {
              ...formFieldsValue,
              pagerArg,
            };
        this.setState({ formValues: formFieldsValue });
        dispatch({
          type: 'material/fetchList',
          payload: values,
        });
      }
    });
  };

  // 删除
  delList = (id, vno) => {
    const {
      dispatch,
      material: { activeKey },
    } = this.props;
    confirm({
      title: '你确定要删除此条信息吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        if (activeKey === '1') {
          dispatch({
            type: 'material/delTemplate',
            payload: { emlMsgTemplateId: id, vno },
          });
        } else if (activeKey === '2') {
          dispatch({
            type: 'material/delInfor',
            payload: { entryInformId: id, vno },
          });
        }
        if (activeKey === '3') {
          dispatch({
            type: 'material/delMat',
            payload: { matPkgId: id, vno },
          });
        }
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  toggleForm = () => {
    const {
      dispatch,
      material: { expandForm },
    } = this.props;
    dispatch({
      type: 'material/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 短信模板
  addemail = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/addEmail?isRenew=1`);
  };

  // 入职告知
  addCareer = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/addcareer?isRenew=2`);
  };

  // 入职材料
  addmaterial = () => {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    router.push(`${tempUrl}/addmaterial?isRenew=3`);
  };

  changeTabPane = activeKey => {
    const { location, dispatch } = this.props;
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });
    dispatch({
      type: 'material/updateModelData',
      payload: { activeKey },
    });
    this.setState({ selectedRows: [] }, () => {
      this.getList(activeKey);
    });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const {
      material: { activeKey },
    } = this.props;

    this.getList(activeKey, pagination.current, pagination.pageSize);
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    await this.resetSearch();
    await this.getList();
    const { dispatch } = this.props;
    dispatch({
      type: 'material/updateModelData',
      payload: { expandForm: false },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      material: { formFieldsValue, activeKey, areaList },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="地区" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.areaId,
              })(
                <Select
                  allowClear
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  showSearch
                  style={{ width: '100%' }}
                  placeholder="请选择地区"
                >
                  {areaList.length &&
                    areaList.map(value => <Option key={value.areaId}>{value.areaName}</Option>)}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="合同类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('contType', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.contType,
              })(
                <DictCode
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  dictType="CONT_TYPE"
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="创建人:" {...this.tableSearchLayout}>
              {getFieldDecorator('creName', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.creName,
              })(<Input placeholder="请输入创建人" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="创建时间:" {...this.tableSearchLayout}>
              {getFieldDecorator('dateArr', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.dateArr,
              })(
                <RangePicker
                  format="YYYY-MM-DD"
                  placeholder={['开始时间', '结束时间']}
                  onChange={this.onTimeChange}
                  style={{ width: '100%' }}
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" htmlType="submit" onClick={() => this.getList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { material } = this.props;
    return material.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      material: { areaList, formFieldsValue, activeKey },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="地区" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.areaId,
              })(
                <Select
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  style={{ width: '100%' }}
                  placeholder="请选择地区"
                >
                  {areaList.length &&
                    areaList.map(value => <Option key={value.areaId}>{value.areaName}</Option>)}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="合同类型：" {...this.tableSearchLayout}>
              {getFieldDecorator('contType', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.contType,
              })(
                <DictCode
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  dictType="CONT_TYPE"
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { location } = this.props;
    const { pathname } = location;
    const tempUrl = pathname.split('/index')[0];
    const {
      material: { data, loading, activeKey, tabList },
    } = this.props;

    const { selectedRowKeys, selectedRows } = this.state;

    const moreMenu1 = record => (
      <Menu>
        {checkPermissions('business:emlMsg:updateEmlMsg') && (
          <Menu.Item key="update">
            <Link
              to={`${tempUrl}/reviseEmail?id=${record.emlMsgTemplateId}&&activeKey=${activeKey}`}
            >
              修改
            </Link>
          </Menu.Item>
        )}
        {checkPermissions('business:emlMsg:deleteEmlMsg') && (
          <Menu.Item key="del" onClick={() => this.delList(record.emlMsgTemplateId, record.vno)}>
            删除
          </Menu.Item>
        )}
      </Menu>
    );

    const moreMenu2 = record => (
      <Menu>
        {checkPermissions('business:entryInform:update') && (
          <Menu.Item key="update">
            <Link to={`${tempUrl}/revisecareer?id=${record.entryInformId}&&activeKey=${activeKey}`}>
              修改
            </Link>
          </Menu.Item>
        )}
        {checkPermissions('business:entryInform:deleteEntry') && (
          <Menu.Item key="del" onClick={() => this.delList(record.entryInformId, record.vno)}>
            删除
          </Menu.Item>
        )}
      </Menu>
    );

    const moreMenu3 = record => (
      <Menu>
        {checkPermissions('business:entryMatPkg:update') && (
          <Menu.Item key="update">
            <Link to={`${tempUrl}/revisematerial?id=${record.matPkgId}&&activeKey=${activeKey}`}>
              修改
            </Link>
          </Menu.Item>
        )}
        {checkPermissions('business:entryMatPkg:delete') && (
          <Menu.Item key="del" onClick={() => this.delList(record.matPkgId, record.vno)}>
            删除
          </Menu.Item>
        )}
      </Menu>
    );

    const columnTemplate = [
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '合同类型',
        dataIndex: 'contTypeName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <Link
              to={`${tempUrl}/detailEmail?id=${record.emlMsgTemplateId}&&activeKey=${activeKey}`}
            >
              查看
            </Link>

            {checkPermissions('business:emlMsg:updateEmlMsg') &&
            checkPermissions('business:emlMsg:deleteEmlMsg') ? (
              <Fragment>
                <Divider type="vertical" />
                <Dropdown overlay={moreMenu1(record)}>
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              </Fragment>
            ) : (
              <Fragment>
                <Authorized authority="business:emlMsg:updateEmlMsg" noMatch={null}>
                  <Divider type="vertical" />
                  <Link
                    to={`${tempUrl}/reviseEmail?id=${
                      record.emlMsgTemplateId
                    }&&activeKey=${activeKey}`}
                  >
                    修改
                  </Link>
                </Authorized>
                <Authorized authority="business:emlMsg:deleteEmlMsg" noMatch={null}>
                  <Divider type="vertical" />
                  <a onClick={() => this.delList(record.emlMsgTemplateId, record.vno)}>删除</a>
                </Authorized>
              </Fragment>
            )}
          </span>
        ),
      },
    ];
    const columnsNotify = [
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '合同类型',
        dataIndex: 'contTypeName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <Link to={`${tempUrl}/detailCareer?id=${record.entryInformId}&&activeKey=${activeKey}`}>
              查看
            </Link>
            {checkPermissions('business:entryInform:update') &&
            checkPermissions('business:entryInform:deleteEntry') ? (
              <Fragment>
                <Divider type="vertical" />
                <Dropdown overlay={moreMenu2(record)}>
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              </Fragment>
            ) : (
              <Fragment>
                <Authorized authority="business:entryInform:update" noMatch={null}>
                  <Divider type="vertical" />
                  <Link
                    to={`${tempUrl}/revisecareer?id=${
                      record.entryInformId
                    }&&activeKey=${activeKey}`}
                  >
                    修改
                  </Link>
                </Authorized>

                <Authorized authority="business:entryInform:deleteEntry" noMatch={null}>
                  <Divider type="vertical" />
                  <a onClick={() => this.delList(record.entryInformId, record.vno)}>删除</a>
                </Authorized>
              </Fragment>
            )}
          </span>
        ),
      },
    ];
    const columnsMaterial = [
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '合同类型',
        dataIndex: 'contTypeName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <Link to={`${tempUrl}/detailmaterial?id=${record.matPkgId}&&activeKey=${activeKey}`}>
              查看
            </Link>
            {checkPermissions('business:entryMatPkg:update') &&
            checkPermissions('business:entryMatPkg:delete') ? (
              <Fragment>
                <Divider type="vertical" />
                <Dropdown overlay={moreMenu3(record)}>
                  <a>
                    更多 <DownOutlined />
                  </a>
                </Dropdown>
              </Fragment>
            ) : (
              <Fragment>
                <Authorized authority="business:entryMatPkg:update" noMatch={null}>
                  <Divider type="vertical" />
                  <Link
                    to={`${tempUrl}/revisematerial?id=${record.matPkgId}&&activeKey=${activeKey}`}
                  >
                    修改
                  </Link>
                </Authorized>

                <Authorized authority="business:entryMatPkg:delete" noMatch={null}>
                  <Divider type="vertical" />
                  <a onClick={() => this.delList(record.matPkgId, record.vno)}>删除</a>
                </Authorized>
              </Fragment>
            )}
          </span>
        ),
      },
    ];
    const tabPane1 = (
      <div>
        <Authorized authority="business:emlMsg:insertEmlMsg" noMatch={null}>
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={this.addemail}
            style={{ marginBottom: 16 }}
          >
            新增
          </Button>
        </Authorized>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={data}
          rowKey="emlMsgTemplateId"
          columns={columnTemplate}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const tabPane2 = (
      <div>
        <Authorized authority="business:entryInform:insert" noMatch={null}>
          <Button
            icon={<PlusOutlined />}
            type="primary"
            style={{ marginBottom: 16 }}
            onClick={this.addCareer}
          >
            新增
          </Button>
        </Authorized>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={data}
          rowKey="entryInformId"
          columns={columnsNotify}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const tabPane3 = (
      <div>
        <Authorized authority="business:entryMatPkg:insert" noMatch={null}>
          <Button onClick={this.addmaterial} type="primary" style={{ marginBottom: 16 }}>
            <PlusOutlined /> 新增
          </Button>
        </Authorized>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={data}
          rowKey="matPkgId"
          columns={columnsMaterial}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );

    const tabPaneTem = ['', tabPane1, tabPane2, tabPane3];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <div className={styles.tableList}>
            <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
              {tabList.map(pane => (
                <TabPane tab={pane.itemName} key={pane.itemCode}>
                  {tabPaneTem[pane.itemCode]}
                </TabPane>
              ))}
            </Tabs>
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
const entrymaterialform = Form.create()(entrymaterial);
export default entrymaterialform;
